import { reactive, onMounted, onBeforeUnmount, getCurrentInstance } from 'vue';
import page from './page.ts';
import { useRouter, useRoute } from 'vue-router';
import { getCustomer } from '@/utils/optionsArr.ts';
export function useListComponent() {
  const router = useRouter();
  const route = useRoute();
  const { proxy } = getCurrentInstance() as any;
  //页面信息
  const dataInfo: any = reactive({
    loading: false, //加载
    loadingMsg: '列表数据加载中', //加载
    table: {
      title: page.title, //表格-标题
      //表格-内容数据
      tbody: [],
      rowKey: 'productID',
      theadCode: 'ProductManager', //basedatatable
      //表格-表头数据
      thead: [],
      //表格-搜索数据
      search: {
        pageIndex: 1, //当前页码
        pageSize: 30, //每页显示数据的数量
        totalCount: 0, //总数量
        queryDataBaseFiled: '', // 关键字查询字段，空值查询全部
        likeWords: '', // 查询关键字，空值查询全部
        beginTime: '', // 日期范围-开始时间
        endTime: '', // 日期范围-结束时间
        onlySelf: 0, // 是否只查询自己创建的，0：查所有、1：只查自己创建的
        isShowDisabled: -1, // 是否显示禁用,-1：显示所有的；0：仅显示未作废的；1 仅显示作废的
        orderByFiled: '', // 排序字段
        orderByType: 0, // 排序方式，0-倒序,1-升序
        state: 0, // 锁定状态筛选：0：全部产品；1：待锁定彩稿的产品；2：业务信息待填写；3设计信息待填写；4：生产信息待填写；5包装信息待填写；6待锁定产品的产品
        customerCode: '', // 客户编号
      },
      //多选
      checkbox: {
        state: true,
        selectable: (row: any) => {
          return true;
        },
        list: [],
      },
      //表格-按钮数据
      btns: [
        {
          title: '导出数据',
          icon: 'Download',
          type: '',
          children: [
            {
              title: '导出当页数据',
              click: () => {
                setLoading('导出当页数据,请稍等');
                exportBtn(dataInfo.table.tbody);
              },
            },
            {
              title: '导出全部数据',
              click: () => {
                setLoading('正在导出全部数据,请稍等');
                proxy.$api.OrderBusniess.GetPageProductList({
                  ...dataInfo.table.search,
                  pageIndex: 1,
                  pageSize: 10000,
                  beginTime: dataInfo.table.search.beginTime || proxy.$getTimeAgo(1, 'years'), // 开始时间
                  endTime: dataInfo.table.search.endTime || proxy.$day(new Date()), // 结束时间
                })
                  .then((res: any) => {
                    exportBtn(res.list);
                  })
                  .catch(() => {
                    dataInfo.loading = false;
                  });
              },
            },
            {
              title: '导出选中数据',
              click: () => {
                setLoading('导出选中数据,请稍等');
                exportBtn(dataInfo.table.checkbox.list);
              },
            },
          ],
        },
        {
          title: '新建',
          icon: 'Plus',
          type: 'primary',
          permission: 'MenuCode1-6-1',
          click: () => {
            getPath({
              path: `${route.path}/add`,
              query: {
                type: 1,
              },
            });
          },
        },
      ],
      //表格-列表搜索
      operation: [
        {
          title: '编辑',
          click: (row: any) => {
            getPath({
              path: `${route.path}/details`,
              query: {
                type: 2,
                productCode: row.productCode,
              },
            });
          },
        },
        {
          title: '复制',
          click: (row: any) => {
            getPath({
              path: `${route.path}/add`,
              query: {
                type: 5,
                productCode: row.productCode,
              },
            });
          },
        },
        {
          title: (row: any) => {
            return row.isDisabled === 0 ? '禁用' : '启用';
          },
          click: (row: any, index: number) => {
            setState(row.productCode, row.isDisabled === 0 ? 6 : 7);
          },
        },
        {
          title: (row: any) => {
            return row.isLockedProduct === 0 ? '锁定' : '解锁';
          },
          click: (row: any, index: number) => {
            setState(row.productCode, row.isLockedProduct === 0 ? 9 : 8);
          },
        },
        {
          title: '删除',
          disabled: (row: any) => {
            return row.isLockedProduct === 1;
          },
          click: (row: any, index: number) => {
            proxy.$messageBox('是否删除当前数据，请确认！', () => {
              proxy.$api.OrderBusniess.DeleteUnusedProductByCode({
                productCode: row.productCode,
              })
                .then((res: any) => {
                  proxy.$message(`删除成功`);
                  getTbody();
                })
                .catch(() => {});
            });
          },
        },
      ],
    },
  });
  const options = reactive({
    //产品状态
    productState: [
      {
        label: '已锁',
        value: 1,
        type: 'success',
      },
      {
        label: '待锁',
        value: 0,
        type: 'info',
      },
    ],
    //禁用状态
    disabledState: [
      {
        label: '禁用',
        value: 1,
        type: 'info',
      },
      {
        label: '启用',
        value: 0,
        type: 'success',
      },
    ],
    //审核状态
    processState: [
      {
        label: '已审',
        value: 1,
        type: 'success',
      },
      {
        label: '待审',
        value: 0,
        type: 'info',
      },
    ],
    //填写状态
    writeState: [
      {
        label: '已填写',
        value: 1,
        type: 'success',
      },
      {
        label: '待填写',
        value: 0,
        type: 'info',
      },
    ],
    //客户信息
    customer: [],
    //产品类型
    productType: [],
    //关联产品
    productView: [],
    //纸箱规格
    paperBox: [],
  });
  // 获取tabs数据
  const getPath = (obj: any, row?: any) => {
    const path = router.resolve(obj);
    if (path.href.includes('/details')) {
      const keyName = `product-${obj.query.productCode}`;
      const keyPath = proxy.$getItem(keyName);
      if (keyPath) {
        proxy.$messageBox('产品已存在打开的编辑，是否继续！', () => {
          goPath();
        });
      } else {
        proxy.$setItem(keyName, 'path');
        goPath();
      }
    } else {
      goPath();
    }

    function goPath() {
      // 在新窗口或标签页中打开目标路径
      const newWindow: any = window.open(path.href, '_blank');
      newWindow;
    }
  };
  // 获取表数据
  const getTbody = () => {
    let _table: any = dataInfo.table;
    setLoading();
    proxy.$api.OrderBusniess.GetPageProductList(_table.search)
      .then((res: any) => {
        _table.tbody = res.list;
        _table.search.totalCount = res.totalCount;
        dataInfo.loading = false;
      })
      .catch(() => {
        dataInfo.loading = false;
      });
  };
  // 导出数据
  const exportBtn = (tbody: any[]) => {
    proxy.$exportData(
      {
        thead: dataInfo.table.thead,
        tbody: tbody,
        fileName: dataInfo.table.title,
      },
      dataInfo,
    );
    dataInfo.loading = false;
  };
  const setLoading = (title: string = '正在获取数据,请稍等...') => {
    if (!dataInfo.loading) {
      dataInfo.loading = true;
      dataInfo.loadingMsg = title;
    }
  };
  //单据状态
  const setState = (productCode: string, state: number = 0) => {
    proxy.$api.OrderBusniess.UpdateProductState({
      state: state, //	锁定状态筛选：0：解锁产品彩稿；1：锁定产品彩稿；2：完成业务信息；3：完成设计信息；4：完成生产信息；5：完成包装信息；6：禁用产品；7：启用产品；8：解锁产品；9：锁定产品；
      productCode: productCode,
    })
      .then((res: any) => {
        getTbody();
      })
      .catch(() => {});
  };
  // 组件挂载后执行
  onMounted(() => {
    getTbody();
    getCustomer(options, 'customer');
  });
  // 组件卸载前执行
  onBeforeUnmount(() => {});
  return { dataInfo, getTbody, options, setState };
}
